#练习作用域之间的转换
m_sub = 0
def mult(a, b):
    m_sub = a * b
    print("函数内是局部变量：", m_sub)
    return m_sub
print(mult(1, 2))
print("函数外是全局变量：", m_sub)

m_sub_1 = 1
def func():
    global m_sub_1
    print(m_sub_1)
    m_sub_1 = 2
    print(m_sub_1)
print(func())
print(m_sub_1)

def a():
    m_sub = 1
    def b():
        nonlocal m_sub
        m_sub = 3
        print(m_sub)
        return b
    b()
    print(m_sub)
a()
print("------")

# 实现一个装饰器，用来输出函数的执行时间
import time
def clock_deco(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"{func.__name__} 执行时长为：{format(end_time - start_time, '.2f')}s")
        return result
    return wrapper

@clock_deco
def cool(a, b):
    num = 0
    while True:
        if num >= a ** b:
            break
        num += 1

cool(5, 10)
print("------")

# 使用装饰器来为斐波那契函数增加缓存
a = {}
def cache_deco(func):
    global a
    def wrap(n):
        if n not in a:
            a[n] = func(n)
        return a[n]
    return wrap

@ cache_deco
def fib(n):
    if n < 2:
        return n
    else:
        return fib(n - 2) + fib(n - 1)

print(fib(10))
print(a)

